/**
 * Created by WeSexyAndWeKnowIt .Inc
 * Member: JackIsSoBig
 * Date: Mar, 30 2012
 * Last update: Mar, 31 2012
 */

package gameGUI;

import gameLogic.BoardState;
import gameLogic.EventHandler;
import gameLogic.Move;
import gameLogic.PlayerType;

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

@SuppressWarnings("serial")
public class GameBoard extends JFrame {
	private JButton[][] btBoard;
	private JLabel lbGameMessage;
	private JLabel lbGameName;
	private JPanel pnGameTitle; // panel for the game title
	private JPanel pnBoardButton; // panel for the game buttons
	private JPanel pnGameMessage; // panel for displaying game massage
	private Container c;
	private ImageIcon imageEmpty;
	private ImageIcon imageX1, imageX2, imageX3;
	private ImageIcon imageO1, imageO2, imageO3;
	private ImageIcon loseIcon;
	private ImageIcon winIcon;
	private ImageIcon inconBanner;
	private BoardState boardState;
	private boolean[][] isAlreadyClicked;
	GameMainMenu menu;
	int tempX, tempY;
	boolean isButtonClick;
	private SoundPlayer player;
	
	public GameBoard(String title, JFrame previousMenu) {
		super(title);
		isButtonClick = false;
		tempX = tempY = -1;
		menu = (GameMainMenu) previousMenu;
		player = new SoundPlayer("sound/battleTheme.mp3");
		inconBanner = new ImageIcon("gui/banner1.jpg");
		// create board 3x3
		btBoard = new JButton[3][3];
		imageX1 = new ImageIcon("gui/X1.png");
		imageX2 = new ImageIcon("gui/X2.png");
		imageX3 = new ImageIcon("gui/X3.png");
		imageO1 = new ImageIcon("gui/O1b.png");
		imageO2 = new ImageIcon("gui/O2b.png");
		imageO3 = new ImageIcon("gui/O3b.png");
		imageEmpty = new ImageIcon("gui/Empty.png");
		loseIcon = new ImageIcon("gui/loseIcon.jpg");// this picture is a troll
		winIcon = new ImageIcon("gui/winIcon.jpg");
		c = getContentPane();

		lbGameMessage = new JLabel("");
		lbGameName = new JLabel(inconBanner);
		// create panel
		pnGameTitle = new JPanel();
		pnGameTitle.add(lbGameName);

		pnGameMessage = new JPanel();
		pnGameMessage.add(lbGameMessage);

		// use grid layout 3x3 for board buttons
		isAlreadyClicked = new boolean[3][3];
		pnBoardButton = new JPanel();
		pnBoardButton.setLayout(new GridLayout(3, 3));
		for (int i = 0; i < btBoard.length; i++)
			for (int j = 0; j < btBoard[i].length; j++) {
				btBoard[i][j] = new JButton(imageEmpty);
				btBoard[i][j].setSize(90, 90);
				pnBoardButton.add(btBoard[i][j]);
				final int x = j;
				final int y = i;
				btBoard[i][j].addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						tempX = x;
						tempY = y;

						isButtonClick = true;
						synchronized(uce) {
							uce.notify();
						}
					}
				});
			}
		pnBoardButton.setSize(300, 300);
		c.add(pnGameTitle, "North");
		c.add(pnBoardButton, "Center");
		c.add(pnGameMessage, "South");

		this.pack();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		// this.setSize(450, 150);
		this.setVisible(false);
		System.out.println("Load Board finished");
		
	}

	/*
	 * values of count 1 <- player1 has 1 cell 2 <- player1 has a thread to win
	 * (2 cells) 3 <- player1 has 3 cells in a win condition 4 <- player1 has 1
	 * cell 5 <- player1 has a thread to win (2 cells) 6 <- player1 has 3 cells
	 * in a win condition
	 */

	public void boardButtonClicked(Move move, int iconType) {
		if (isAlreadyClicked[move.y][move.x]) {
			return;
		}
		// test X and O icons
		// if (pair.x > pair.y) {
		// showWinMessage("Player 2");
		// boardState = BoardState.O;
		// this.setVisible(false);
		// menu.setVisible(true);
		// } else
		// boardState = BoardState.X;
		// end test
		switch (iconType) {
		case 1:
			btBoard[move.y][move.x].setIcon(imageX1);
			break;
		case 2:
			btBoard[move.y][move.x].setIcon(imageX2);
			break;
		case 3:
			btBoard[move.y][move.x].setIcon(imageX3);
			break;
		case 4:
			btBoard[move.y][move.x].setIcon(imageO1);
			break;
		case 5:
			btBoard[move.y][move.x].setIcon(imageO2);
			break;
		case 6:
			btBoard[move.y][move.x].setIcon(imageO3);
			break;

		}
		isAlreadyClicked[move.y][move.x] = true;
	}

	/**
	 * Require: the player type of the winner, name of the player If computer
	 * wins, send AI type, second parameter is null If human wins, send HUMAN
	 * type as well as the second parameter to print the winner name If draw,
	 * send null for both parameters
	 * 
	 * @param playerType
	 * @param playerName
	 */
	// change String player -> PlayerType playerType - Jack, April 5, 2010
	public void showWinMessage(PlayerType playerType, String playerName) {
		if (playerType != PlayerType.HUMAN && playerType != PlayerType.HUMAN_AIDED && playerName != null) {
			// AI wins
			JOptionPane.showMessageDialog(null, "You lose. Try again",
					"Game end", 1, loseIcon);
			return;
		} else if (playerType == PlayerType.HUMAN || playerType == PlayerType.HUMAN_AIDED) {
			// human wins
			JOptionPane
					.showMessageDialog(null, playerName
							+ " won. You win a date with me <3", "Game end", 1,
							winIcon);
			return;
		} else if (playerType==null && playerName==null){
			// draw game
			JOptionPane.showMessageDialog(null,
					"Draw game.Try harder next time.", "Game end", 1, loseIcon);
		}		
	}

	public UserClickEventHandler uce = new UserClickEventHandler();

	public class UserClickEventHandler implements EventHandler {
		@Override
		public void actionPerformed(Object arg) {

			synchronized (uce) {
				if (!isButtonClick)
					try {
						uce.wait();
						System.out.println("sleeping...");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				((Move) arg).x = tempX;
				((Move) arg).y = tempY;
			}
			// Move move= new Move(tempX,tempY,null);
			isButtonClick = false;
			tempX = tempY = -1;
		}
	}

	public BoardUpdatedEventHandler bue = new BoardUpdatedEventHandler();

	public class BoardUpdatedEventHandler implements EventHandler {
		@Override
		public void actionPerformed(Object arg) {
			Move m = (Move) arg;
			boardButtonClicked(m, (m.v == BoardState.X) ? Move.xIconType
					: Move.yIconType);
			System.out.println("GUI update: " + m);
		}
	}

	public void resetBoard() {
		for (int i = 0; i < btBoard.length; i++)
			for (int j = 0; j < btBoard[i].length; j++) {
				btBoard[i][j].setIcon(imageEmpty);
				isAlreadyClicked[i][j] = false;
			}
	}
	public void playBattleTheme(){
		player.play();
	}
	public void prepareNewGame() {
		player.close();
		this.dispose();
		menu.setVisible(true);
	}
}
